# coding:utf-8
# @Time : 2021/5/7 9:46 
# @Author : minuy
# @File : verification_code.py
# python -m pip install --upgrade Pillow
import hashlib
from io import BytesIO
import random
import string
from PIL import Image, ImageFont, ImageDraw
from flask import make_response, session, request

from app.api import api
from app.api.interface import api_result
from app.libs.md5_tool import get_md5_value


class ImageCode:
    def gene_text(self):
        """
        生成4位验证码
        :return: 4位验证码
        """
        # ascii_letters是生成所有字母 digits是生成所有数字 0-9
        return ''.join(random.sample(string.ascii_letters + string.digits, 4))

    def random_color(self):
        """
        随机颜色
        :return: 随机颜色
        """
        return random.randint(32, 127), random.randint(32, 127), random.randint(32, 127)

    def draw_lines(self, draw, num, width, height):
        """
        划线
        :param draw:
        :param num:
        :param width:
        :param height:
        :return:
        """
        for num in range(num):
            x1 = random.randint(0, width / 2)
            y1 = random.randint(0, height / 2)
            x2 = random.randint(0, width)
            y2 = random.randint(height / 2, height)
            draw.line(((x1, y1), (x2, y2)), fill='black', width=1)

    def get_verify_code(self):
        """
        生成验证码图形
        :return: 图片
        """
        code = self.gene_text()
        # 图片大小120×50
        width, height = 120, 50
        # 新图片对象
        im = Image.new('RGB', (width, height), 'white')
        # 字体
        font = ImageFont.truetype('app/static/arial.ttf', 40)
        # draw对象
        draw = ImageDraw.Draw(im)
        # 绘制字符串
        for item in range(4):
            draw.text((5 + random.randint(-3, 3) + 23 * item, 5 + random.randint(-3, 3)),
                      text=code[item], fill=self.random_color(), font=font)
        # 划线
        self.draw_lines(draw, 2, width, height)
        return im, code

    def get_image_code(self):
        image, code = self.get_verify_code()
        # 图片以二进制形式写入
        buf = BytesIO()
        image.save(buf, 'jpeg')
        buf_str = buf.getvalue()
        # 把buf_str作为response返回前端，并设置首部字段
        response = make_response(buf_str)
        response.headers['Content-Type'] = 'image/gif'
        # 将验证码字符串储存在session中
        session['captcha'] = code
        return response


@api.route('/verificationCode')
def captcha():
    """
    验证码
    :return: 返回一个验证码
    """
    image_code = ImageCode()
    return image_code.get_image_code()


@api.route('/phoneVerificationCode')
def phone_captcha():
    """
    生成验证码并保存到客户端
    :return: 验证码的MD5值
    """
    print(request.args)
    if request.args:
        phone = request.args.get('phone')
        if phone:
            code = ""
            for i in range(6):
                ch = chr(random.randrange(ord('0'), ord('9') + 1))
                code += ch
            code = str(code)
            print(phone, '获取的验证码：', code)
            m5 = get_md5_value(code)
            res = {
                'code': m5
            }
            return api_result(data=res)
    return api_result(code=403,message='参数不正确')
